package cn.hdufocus.focus_helper.controller;

import cn.hdufocus.focus_helper.annotation.MonitorRequest;
import cn.hdufocus.focus_helper.bean.ResponseBean;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class FileController {
    private final String tempPath = new ApplicationHome(this.getClass()).getSource().getParentFile().getPath() + "/file/";


    @PostMapping()
    public ResponseBean upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseBean(405, "上传失败", null);
        }

        String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + file.getOriginalFilename();
        File dest = new File(tempPath + fileName);
        try {
            file.transferTo(dest);
            return new ResponseBean(200, "上传成功", fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseBean(405, "上传失败", null);
    }

    @GetMapping("/{fileName}")
    public ResponseBean download(HttpServletResponse response, @PathVariable("fileName") String filename) throws IOException {
        String path = tempPath + filename;
        response.reset();
        response.setHeader("Content-Disposition", "attachment;fileName=" + path);
        InputStream inStream = new FileInputStream(path);
        OutputStream os = response.getOutputStream();
        byte[] buff = new byte[1024];
        int len = -1;
        while ((len = inStream.read(buff)) > 0) {
            os.write(buff, 0, len);
        }
        os.flush();
        os.close();
        inStream.close();
        return new ResponseBean(200,"ok",null);
    }
}
